package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;

import com.itheima.reggie.mapper.EmployeeMapper;

import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

//员工管理模块
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    //员工登录
    @Override
    public ResultInfo login(String username, String password) {
    //1.根据username查询mapper
        Employee employee = employeeMapper.findByUsername(username);
        if (employee==null){
            System.out.println("此用户名不存在");
        }
        //2.密码比较
        String md5 = SecureUtil.md5(password);
        if (!StrUtil.equals(md5,employee.getPassword())){
            return ResultInfo.error("密码错误");
        }
        //3.判断账号是否禁用
        if (employee.getStatus()==0){
            return ResultInfo.error("此账号被禁用,请联系管理员");
        }
        return ResultInfo.success(employee);
    }

    //员工列表
    @Override
    public List<Employee> findList(String name) {
      //调用mapper查询
        return employeeMapper.findList(name);
    }

    //新增员工
    @Override
    public void save(Employee employee) {
        //1.补全员工信息
        //1-1 使用雪花的id生成器
        //long id = IdUtil.getSnowflake(1, 1).nextId();
        //employee.setId(id);
        ////1-2初始密码
        //String pwd = SecureUtil.md5(Constant.INIT_PASSWORD);
        //employee.setPassword(pwd);
        ////1-3员工状态
        //employee.setStatus(Employee.STATUS_ENABLE); //默认为1
        ////1-4创建,更新时间
        //employee.setCreateTime(new Date()); //创建时间    //todo 暂时写死
        //employee.setUpdateTime(new Date()); //修改时间
        ////1-5创建,更新人
        //employee.setCreateUser(1L); //是谁创建的  // todo 暂时写死
        //employee.setUpdateUser(1L); //是谁更新的
        //2.调用mapper添加
        employeeMapper.save(employee);
    }

    //回显员工
    @Override
    public Employee findById(Long id) {
        //直接mapper查询
        return employeeMapper.findById(id);
    }

    //修改员工
    @Override
    public void updateById(Employee employee) {
        //1.补全信息
        //employee.setUpdateUser(1L); //todo 暂时写死
        //employee.setUpdateTime(new Date());
        //3.调用mapper修改
        employeeMapper.updateById(employee);
    }
}
